package com.qu.waibao.home.activity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.HomeService;
import com.qu.waibao.home.HomeFragment;
import com.qu.waibao.home.adpater.CallAdapter;
import com.qu.waibao.home.adpater.HomeCallAdapter;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.activity.HelpDetailActivity;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.TDevice;
import com.qu.waibao.widget.RecyclerRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.xutils.x;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class CallActivity extends BaseActivity implements View.OnClickListener,
        BaseRecyclerAdapter.OnItemClickListener,RecyclerRefreshLayout.SuperRefreshLayoutListener
        {
    @BindView(R.id.tv_publish)
    TextView tv_publish;
    @BindView(R.id.tv_all)
    TextView tv_all;
    @BindView(R.id.mRecyclerRefreshLayout)
    RecyclerRefreshLayout mRecyclerRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.ll_tips)
    LinearLayout ll_tips;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    private HomeCallAdapter adapter;
    private String servicefrom = "1";
    private int pageNum = 1;
    private String latitude = "";
    private String longitude = "";
    private boolean isRefreshing = true;
    private HomeService homeService;
    @Override
    protected int getContentView() {
        return R.layout.activity_call;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mRecyclerRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mRecyclerRefreshLayout.setSuperRefreshLayoutListener(this);
        if(AppConfig.getInt("card") == 2){ //修理工
            ll_tips.setVisibility(View.GONE);
            iv_publish.setVisibility(View.GONE);
            servicefrom = "2";
        }
        if(LocationUtils.Mylocation != null){
            latitude = String.valueOf(LocationUtils.Mylocation.getLatitude());
            longitude = String.valueOf(LocationUtils.Mylocation.getLongitude());
        }
        initBanner();
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new HomeCallAdapter(this, BaseRecyclerAdapter.ONLY_FOOTER);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        if(adapter.getItems().size() == 0){
            mRecyclerRefreshLayout.setRefreshing(true);
            onRefreshing();
        }
        adapter.setOnItemClickListener(this);
    }
    @OnClick({R.id.tv_publish,R.id.tv_all,R.id.ll_back,R.id.iv_publish})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_publish:
                tv_publish.setTextColor(TDevice.getColor(getResources(),R.color.whites));
                tv_publish.setBackgroundResource(R.color.colorPrimaryDark);
                tv_all.setTextColor(TDevice.getColor(getResources(),R.color.text_222));
                tv_all.setBackgroundResource(R.color.whites);
                servicefrom = "1";
                onRefreshing();
                break;
            case R.id.tv_all:
                tv_publish.setTextColor(TDevice.getColor(getResources(),R.color.text_222));
                tv_publish.setBackgroundResource(R.color.whites);
                tv_all.setTextColor(TDevice.getColor(getResources(),R.color.whites));
                tv_all.setBackgroundResource(R.color.colorPrimaryDark);
                servicefrom = "2";
                isRefreshing = true;
                onRefreshing();
                break;
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_publish:
                startActivity(new Intent(this,PublishActivity.class));
                break;
        }
    }

    public void initBanner(){
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if(homeService != null) {
                    String textInfoid = homeService.getBanner().get(position).getTextInfoid();
                    Intent intent = new Intent(CallActivity.this, HelpDetailActivity.class);
                    intent.putExtra("textInfoid", textInfoid);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onItemClick(int position, long itemId) {
          String serviceid = adapter.getItems().get(position).getServiceid();
          Intent intent = new Intent(this,PublishDetailActivity.class);
          intent.putExtra("serviceid",serviceid);
          startActivity(intent);
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        pageNum = 1;
        requestData();
    }

    @Override
    public void onLoadMore() {
        isRefreshing = false;
        pageNum++;
        adapter.setState(BaseRecyclerAdapter.STATE_LOAD_MORE,true);
        requestData();
        Log.e("TAG","onLoadMore-------------"+isRefreshing);
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            HomeService.BannerBean bean = (HomeService.BannerBean) path;
            Glide.with(context).load(NetManager.getFullUrl(bean.getPhoto())).into(imageView);
        }
    }


    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.service_list_get);
        map.put("userid",AppConfig.getString("userid"));
        map.put("servicecategoryid","1");
        map.put("servicefrom",servicefrom);
        map.put("ordertype","");
        map.put("state","");
        map.put("latitude",latitude);
        map.put("longitude",longitude);
        map.put("pagenum",pageNum+"");
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                Log.e("TAG","onSuccess"+isRefreshing);
                homeService = GsonUtil.createGson().fromJson(result,HomeService.class);
                    if(homeService.getBanner().size() > 0) {
                        banner.setImages(homeService.getBanner());
                        banner.start();
                    }
                    if (isRefreshing) {
                        adapter.clear();
                        adapter.addAll(homeService.getService());
                        if (homeService.getService().size() < 12) {
                            adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
                        }
                    } else {
                        adapter.addAll(homeService.getService());
                        if (homeService.getService().size() < 12) {
                            adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
                        }
                        if (homeService.getService().size() == 0) {
                            pageNum--;
                        }
                    }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
               if(pageNum > 1){
                   pageNum--;
                   onComplate();
               }
            }

            @Override
            public void onFinished() {
                onComplate();
            }
        });
    }

    public void onComplate(){
        mRecyclerRefreshLayout.onComplete();
        isRefreshing = false;
    }
}
